<?php

class CityDAO {
    // Syndesh kai epilogh bashs
    function __construct(){
        $this->connection = mysql_connect('127.0.0.1', 'root', '')
                or die('Could not connect: ' . mysql_error());
        mysql_select_db('travelbook', $this->connection)
                or die('Could not select database');
    }

    // Kleisimo syndeshs me thn bash
    function __destruct(){
        if(isset($connection))
            mysql_close($connection);
    }

    // Epistrefei thn xwra mias polhs
    function retrieveCountry($cityName){
        $query = "SELECT name FROM country WHERE countryid=(SELECT countryid FROM city WHERE name='$cityName')";
        $result = mysql_query($query);
        if(mysql_num_rows($result) == 0){
            return '';
        }
        else{
            $row = mysql_fetch_array($result);
            return $row['name'];
        }
    }

    // Epistrefei tis poleis poy arxizoyn me thn symboloseira poy dothike
    function retrieveCities($prefix){
        $query = "SELECT name FROM city WHERE name LIKE '$prefix%'";
        $result = mysql_query($query);
        $cities = array();
        if(mysql_num_rows($result) == 0){
            return '';
        }
        else{
            $i = 0;
            while($row = mysql_fetch_array($result)){
                $cities[$i] = $row['name'];
                $i++;
            }
            return $cities;
        }
    }

    function retrieveName($id){
        $query = "SELECT name FROM city WHERE cityid='$id'";
        $result = mysql_query($query);
        if(mysql_num_rows($result) == 0){
            return '';
        }
        else{
            while($row = mysql_fetch_array($result)){
                $name = $row['name'];
            }
            return $name;
        }
    }

    function retrieveId($name){
        $query = "SELECT cityid FROM city WHERE name='$name'";
        $result = mysql_query($query);
        if(mysql_num_rows($result) == 0){
            return '';
        }
        else{
            while($row = mysql_fetch_array($result)){
                $name = $row['cityid'];
            }
            return $name;
        }
    }

    function checkCity($name){
        $query = "SELECT * FROM city WHERE name='$name'";
        $result = mysql_query($query);
        if(mysql_num_rows($result) == 0){
            return false;
        }
        else{
            return true;
        }
    }

    function insertCity($city,$countryId){

        $query = "INSERT INTO city VALUES(default,'$countryId','$city')";
        mysql_query($query);
    }
}
?>
